﻿Imports System.Data
Imports Sybase.Data.AseClient
Imports System.IO
Imports System.Text
Imports System.Xml 
imports System.Windows.Media
Imports System.ComponentModel   
Imports System.Collections.ObjectModel   
Imports Microsoft.Office.Interop.Excel
Imports System.Reflection  


Class CMLiquidez


Private  RUTAARCHIVO      As String 
Private  NOMBREARCHIVO    As String 
Private  TLOADERCOMMAND   As String 
Private  PARAMTLOADER     As String 

    
Dim negocio                As  CLiquidezServicio 
Private  lstFondosInter    As New List(Of CFondoIntermediario)
Private  lstIntermediarios As New List(Of CIntermediario)


 'Estas constantes se relacionan con las columnas (posiciones en el Grid) no con la posicion de las propiedades. 

  Public Const   LIMITECOLUMNASOLOCOPIADO As Integer = 6
  Public Const   INICIOBLOQUEINTERMEDIARIOS As Integer = 7
  Public Const   FINCIOBLOQUEINTERMEDIARIOS As Integer = 15

  Public Const   LIMITECOLUMNASOLOCOPIADO_MON As Integer = 0
  Public Const   LIMITERENGLONSOLOCOPIADO_MON As Integer = 1
  Public Const   INICIOBLOQUEINTERMEDIARIOS_MON As Integer = 1
  Public Const   FINCIOBLOQUEINTERMEDIARIOS_MON As Integer = 9


   Private Enum ConfigMenuContextual
     COPIADO_Y_PEGADO = 0
     SOLOCOPIADO     = 1    
  End Enum

 
 


  #Region "EVENTOS"

    #Region "EVENTOS DE CLASE"

            Private Sub Page_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
               Me.imgRefrescar.Focus  
            End Sub

            Protected Overrides Sub Finalize()
                MyBase.Finalize()
            End Sub

    #End Region

    #Region "GRID PRINCIPAL"

            Private Sub grdFondoInter_MouseRightButtonUp(ByVal sender As System.Object , ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles grdFondoInter.MouseRightButtonUp
   
              Dim objDepend As DependencyObject = e.OriginalSource 
              Dim celda As DataGridCell = Nothing 


              Me.grdFondoInter.ContextMenu = Nothing  
              While not objDepend is Nothing 

                    If objDepend.GetType().Name = "DataGridCell" then 
                       celda = objDepend           
           
                       If celda.IsSelected = false  then               
                           Me.grdFondoInter.UnselectAllCells () 
                           celda.IsSelected = True                                                                                                                                                              
                       End If                              
           
                       celda.Focus ()
                  
                       If celda.Column.DisplayIndex <= LIMITECOLUMNASOLOCOPIADO or celda.Column.DisplayIndex > FINCIOBLOQUEINTERMEDIARIOS     then 'Condición según el negocio
                          Me.grdFondoInter.ContextMenu = AgregarMenuContextual (ConfigMenuContextual.SOLOCOPIADO)  
                       Else
                          Me.grdFondoInter.ContextMenu = AgregarMenuContextual (ConfigMenuContextual.COPIADO_Y_PEGADO)   
                       End If    

                       Exit While 
                    End If

                   objDepend = VisualTreeHelper.GetParent (objDepend)   
              End While

 


            End Sub

                Private Sub grdFondoInter_PreviewKeyDown(ByVal sender As System.Object , ByVal e As System.Windows.Input.KeyEventArgs) Handles grdFondoInter.PreviewKeyDown
   

                    If e.Key = Key.Apps then 
          
                        If grdFondoInter.CurrentCell.Column.DisplayIndex <= LIMITECOLUMNASOLOCOPIADO  or grdFondoInter.CurrentCell.Column.DisplayIndex > FINCIOBLOQUEINTERMEDIARIOS   then 'Condición según el negocio
                              Me.grdFondoInter.ContextMenu = AgregarMenuContextual (ConfigMenuContextual.SOLOCOPIADO)   
                           Else
                              Me.grdFondoInter.ContextMenu = AgregarMenuContextual (ConfigMenuContextual.COPIADO_Y_PEGADO)   
                           End If    
                    End If



                    If Keyboard.Modifiers = ModifierKeys.Control andalso e.Key = Key.C Then
                       Try           
                          If copiarCeldas(Me.grdFondoInter, "General.CFondoIntermediario") = False then 
                              e.Handled = True 'Se indica que el evento ha sido manejado antes del mensaje, ya que este renderiza la pantalla
                              MessageBox.Show ("El rango de celdas seleccionado no es correcto","Copiar celdas",MessageBoxButton.OK,MessageBoxImage.Exclamation) 
                          End If

                       Catch ex As Exception
                                 e.Handled = True
                                MessageBox.Show("Error TI500. Error al intentar copiar celdas: " & ex.Message, "Copiado", MessageBoxButton.OK, MessageBoxImage.Error)
                       End Try

                   End If

                    If Keyboard.Modifiers = ModifierKeys.Control andalso e.Key = Key.V Then
       
                       Try
                          Dim col As Integer = Me.grdFondoInter.CurrentCell.Column.DisplayIndex   
                          Dim row As Integer = Me.grdFondoInter.Items.IndexOf  (CType(Me.grdFondoInter.CurrentCell.Item,CFondoIntermediario ))                        
                          Dim celda As DataGridCell  = ObtenerCelda (Me.grdFondoInter,row,col) 

                          If col > LIMITECOLUMNASOLOCOPIADO and col <= FINCIOBLOQUEINTERMEDIARIOS then 
             
                             Me.grdFondoInter.CancelEdit ()                          
                             pegarDatos(Me.grdFondoInter,"General.CFondoIntermediario",CUtileria.Condiciones.sinCondicion)  
                             e.Handled = True                                                                                          
                          End If
           
            

                       Catch ex As Exception
                                Me.grdFondoInter.CancelEdit (DataGridEditingUnit.Cell)  
                                e.Handled = True 
                                MessageBox.Show(ex.Message, "Pegar celdas", MessageBoxButton.OK, MessageBoxImage.Exclamation )                       
                        End Try

                    End If

                    If e.Key = Key.Delete  Then
                  
                       Try
                          Dim col As Integer = Me.grdFondoInter.CurrentCell.Column.DisplayIndex   
                          Dim row As Integer = Me.grdFondoInter.Items.IndexOf  (CType(Me.grdFondoInter.CurrentCell.Item,CFondoIntermediario ))                        
                          Dim celda As DataGridCell  = ObtenerCelda (Me.grdFondoInter,row,col) 
                      

                          If Not celda.IsEditing
                                  borraDatosSeleccionados(Me.grdFondoInter) 
                                  Me.grdFondoInter.UnselectAllCells  () 
                          end if
                      
                                  
                       Catch ex As Exception
                                MessageBox.Show("Error TI500. " & ex.Message, "Borrar contenido de celdas", MessageBoxButton.OK, MessageBoxImage.Error)
                        End Try

                    End If

    

                End Sub


            Private Sub grdFondoInter_CellEditEnding(ByVal sender As System.Object , ByVal e As System.Windows.Controls.DataGridCellEditEndingEventArgs) Handles grdFondoInter.CellEditEnding
                  Dim txtContenidoCelda As Object 
  
                  Try
           
                      If e.EditAction <> DataGridEditAction.Cancel   then 
  
                          If not sender.CurrentItem is Nothing then
      
                              txtContenidoCelda    = sender.Columns(e.Column.DisplayIndex).GetCellContent(ctype( e.Row.Item,CFondoIntermediario))
                                   
                              If Not IsNumeric (txtContenidoCelda.Text) then                                  
                                 CType(sender,DataGrid).CancelEdit (DataGridEditingUnit.Cell)                                                              
                              else

                                 Dim MontoMax       As Double =   lstIntermediarios(CIntermediario.enumConceptoInterLiq.Monto_maximo).Columna((e.Column.DisplayIndex  -   INICIOBLOQUEINTERMEDIARIOS + 1))
                                 Dim MontoActual    As Double =   lstIntermediarios(CIntermediario.enumConceptoInterLiq.Monto_actual).Columna ((e.Column.DisplayIndex  -   INICIOBLOQUEINTERMEDIARIOS + 1)) 
                                 Dim MontoAnteFondo As Double =   ctype( e.Row.Item,CFondoIntermediario)(e.Column.DisplayIndex)
                                 Dim montoPosible   As Double =   MontoActual - MontoAnteFondo + Convert.ToDouble (txtContenidoCelda.Text)
                                                                                                                              
                                 If  MontoMax   < montoPosible  then 
                                       CType(sender,DataGrid).CancelEdit (DataGridEditingUnit.Cell)                                         
                                 else
                                         
                                       Dim saldoCalc As Double = ctype( e.Row.Item,CFondoIntermediario).SaldoDecalogCalculado + MontoAnteFondo - Convert.ToDouble (txtContenidoCelda.Text)

                                       If (saldoCalc < 0) and Convert.ToDouble (txtContenidoCelda.Text) > 0 then 
                                           If MessageBox.Show ("El fondo: " & ctype( e.Row.Item,CFondoIntermediario).CodFondo & " quedará corto.","Fondo con saldo en corto",MessageBoxButton.OKCancel,MessageBoxImage.Question ) = MessageBoxResult.Cancel then 
                                              CType(sender,DataGrid).CancelEdit (DataGridEditingUnit.Cell)   
                                           End If                                           
                                       End If
                                                                                                                                                                                                                                                              
                                 End If                              

                              End If
                              

                          else
                              CType(sender,DataGrid).CancelEdit (DataGridEditingUnit.Cell)  
                          End If
  

                         End If

  
                Catch ex As Exception
                   'No se necesita el manejo de la excepción, en todo caso se puede mostrar un mensaje personalizado (lo cual quedará a petición del usuario).
                End Try

            End Sub
            
            Private Sub grdFondoInter_BeginningEdit(ByVal sender As System.Object , ByVal e As System.Windows.Controls.DataGridBeginningEditEventArgs) Handles grdFondoInter.BeginningEdit
               If e.Column.DisplayIndex > FINCIOBLOQUEINTERMEDIARIOS  THEN 
                  e.Cancel = True 
              End If
            End Sub


    #End Region

    #Region "GRID MONTOS"

        Private Sub grdMonMax_BeginningEdit(ByVal sender As System.Object , ByVal e As System.Windows.Controls.DataGridBeginningEditEventArgs) Handles grdMonMax.BeginningEdit
                  If e.Row.GetIndex  = CIntermediario.enumConceptoInterLiq.Monto_actual    or e.Row.GetIndex   = CIntermediario.enumConceptoInterLiq.Monto_remanente    then             
                    e.Cancel = True   
                  End If
        End Sub

        Private Sub grdMonMax_CellEditEnding(ByVal sender As System.Object , ByVal e As System.Windows.Controls.DataGridCellEditEndingEventArgs) Handles grdMonMax.CellEditEnding
           Dim txtContenidoCelda As Object 
  
              Try
           
                  If e.EditAction <> DataGridEditAction.Cancel   then 
  
                      If not sender.CurrentItem is Nothing then
      
                          txtContenidoCelda    = sender.Columns(e.Column.DisplayIndex).GetCellContent(sender.CurrentItem)
                                   
                          If Not IsNumeric (txtContenidoCelda.Text) then 
                            CType(sender,DataGrid).CancelEdit (DataGridEditingUnit.Cell)  
                         End If

                      else
                          CType(sender,DataGrid).CancelEdit (DataGridEditingUnit.Cell)  
                      End If
  

                     End If

  
            Catch ex As Exception

            End Try

        End Sub

        Private Sub grdMonMax_MouseRightButtonUp(ByVal sender As System.Object , ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles grdMonMax.MouseRightButtonUp


         Dim puedoPegar As Boolean = True  
         Dim objDepend As DependencyObject = e.OriginalSource 
         Dim celda As DataGridCell = Nothing 


          Me.grdMonMax.ContextMenu = Nothing  
          While not objDepend is Nothing 

                If objDepend.GetType().Name = "DataGridCell" then 
                   celda = objDepend           
           
                   If celda.IsSelected = false  then               
                       Me.grdMonMax.UnselectAllCells () 
                       celda.IsSelected = True                                                                                                                                                              
                   End If                              

           
                   celda.Focus ()

                  
                    For Each celdaSel As DataGridCellInfo In grdMonMax.SelectedCells 
                       If celdaSel.Column.DisplayIndex = LIMITECOLUMNASOLOCOPIADO_MON  or  CType(celdaSel.Item,CIntermediario).CveConcepto = CIntermediario.enumConceptoInterLiq.Monto_actual _
                          or CType(celdaSel.Item,CIntermediario).CveConcepto = CIntermediario.enumConceptoInterLiq.Monto_remanente then 
                          puedoPegar = False 
                          Exit For      
                       End If
                    Next


                   If puedoPegar = True then 
                      For Each celdaSel As DataGridCellInfo In grdMonMax.SelectedCells 
                              Me.grdMonMax.ContextMenu =  AgregarMenuContextualMontosMax (0)
                      Next
                   Else
                      For Each celdaSel As DataGridCellInfo In grdMonMax.SelectedCells 
                           Me.grdMonMax.ContextMenu =  AgregarMenuContextualMontosMax (1)
                      Next
                   End if 
          
                   Exit While 
                End If

               objDepend = VisualTreeHelper.GetParent (objDepend)   
          End While



        End Sub

        Private Sub grdMonMax_PreviewKeyDown(ByVal sender As System.Object , ByVal e As System.Windows.Input.KeyEventArgs) Handles grdMonMax.PreviewKeyDown

    
            'Desplegado del menú contextual
            If e.Key = Key.Apps then 
          
                               
                If (grdMonMax.CurrentCell.Column.DisplayIndex > LIMITECOLUMNASOLOCOPIADO_MON) _
                   and (grdMonMax.Items.IndexOf (grdMonMax.CurrentItem) < LIMITERENGLONSOLOCOPIADO_MON ) then 'Condición según el negocio            
                      Me.grdMonMax.ContextMenu = AgregarMenuContextual (0)                    '1 sólo copiado
                Else                                                                           '0 copiado y pegado
                      Me.grdMonMax.ContextMenu = AgregarMenuContextual (1)
                End If    

            End If


            'Copiado de celdas
            If Keyboard.Modifiers = ModifierKeys.Control andalso e.Key = Key.C Then
               Try           
                  If copiarCeldas(Me.grdMonMax, "General.CIntermediario") = False then 
                      e.Handled = True 'Se indica que el evento ha sido manejado antes del mensaje, ya que este renderiza la pantalla
                      MessageBox.Show ("El rango de celdas seleccionado no es correcto","Copiar celdas",MessageBoxButton.OK,MessageBoxImage.Exclamation) 
                  End If

               Catch ex As Exception
                         e.Handled = True
                        MessageBox.Show("Error TI500. Error al intentar copiar celdas: " & ex.Message, "Copiado", MessageBoxButton.OK, MessageBoxImage.Error)
               End Try

           End If


           'Pegado de celdas
            If Keyboard.Modifiers = ModifierKeys.Control andalso e.Key = Key.V Then
       
               Try
                  Dim col As Integer = Me.grdMonMax.CurrentCell.Column.DisplayIndex   
                  Dim row As Integer = Me.grdMonMax.Items.IndexOf  (CType(Me.grdMonMax.CurrentCell.Item,CIntermediario ))                        
                  Dim celda As DataGridCell  = ObtenerCelda (Me.grdMonMax,row,col) 

                  If col > LIMITECOLUMNASOLOCOPIADO_MON  then 
             
                     Me.grdMonMax.CancelEdit ()                          
                     pegarDatos(Me.grdMonMax,"General.CIntermediario",CUtileria.Condiciones.pegarMonMaxLiq)  
                     e.Handled = True                                                                                          
                  End If
           
            

               Catch ex As Exception
                        Me.grdMonMax.CancelEdit (DataGridEditingUnit.Cell)  
                        e.Handled = True 
                        MessageBox.Show(ex.Message, "Pegar celdas", MessageBoxButton.OK, MessageBoxImage.Exclamation )                       
                End Try

            End If



            'Borrado de celdas
            If e.Key = Key.Delete  Then
                  
               Try

                   Dim col As Integer = Me.grdMonMax.CurrentCell.Column.DisplayIndex   
                   Dim row As Integer = Me.grdMonMax.Items.IndexOf  (CType(Me.grdMonMax.CurrentCell.Item,CIntermediario ))                        
                   Dim celda As DataGridCell  = ObtenerCelda (Me.grdMonMax,row,col) 

                   If celda.IsEditing = False then 
                       borraDatosSeleccionadosMontoMax(Me.grdMonMax) 
                       Me.grdMonMax.UnselectAllCells  () 
                   end if
           
               Catch ex As Exception
                        MessageBox.Show("Error TI500. " & ex.Message, "Borrar contenido de celdas", MessageBoxButton.OK, MessageBoxImage.Error)
                End Try

            End If



        End Sub

    #End Region

    #Region "MENU CONTEXTUAL"

            Private Sub mnuPegar_click(sender As Object, e As RoutedEventArgs)
                 Try
                    pegarDatos(Me.grdFondoInter,"General.CFondoIntermediario",CUtileria.Condiciones.sinCondicion)           
                 Catch ex As Exception
                            MessageBox.Show("Error TI500. " & ex.Message, "Pegar celdas", MessageBoxButton.OK, MessageBoxImage.Exclamation)
                 End Try
   
            End Sub 

            Private Sub mnuCopiar_click(sender As Object, e As RoutedEventArgs)
    
                 Try
                    If copiarCeldas(Me.grdFondoInter, "General.CFondoIntermediario" ) = False then 
                       MessageBox.Show ("El rango de celdas seleccionado no es correcto","Copiar celdas",MessageBoxButton.OK,MessageBoxImage.Exclamation) 
                    End If
                 Catch ex As Exception
                            MessageBox.Show("Error TI500. Error al intentar copiar celdas: " & ex.Message, "Copiado", MessageBoxButton.OK, MessageBoxImage.Error)
                 End Try
 
            End Sub 

            Private Sub mnuPegarMontoMax_click(sender As Object, e As RoutedEventArgs)

                Try
                    pegarDatos(Me.grdMonMax,"General.CIntermediario",CUtileria.Condiciones.pegarMonMaxLiq)           
                 Catch ex As Exception
                            MessageBox.Show("Error TI500. " & ex.Message, "Pegar celdas", MessageBoxButton.OK, MessageBoxImage.Exclamation)
                 End Try


            End Sub

            Private Sub mnuCopiarMontoMax_click(sender As Object, e As RoutedEventArgs)
                Try
                    If copiarCeldas(Me.grdMonMax,"General.CIntermediario") = False then 
                       MessageBox.Show ("El rango de celdas seleccionado no es correcto","Copiar celdas",MessageBoxButton.OK,MessageBoxImage.Exclamation) 
                    End If
                 Catch ex As Exception
                            MessageBox.Show("Error TI500. Error al intentar copiar celdas: " & ex.Message, "Copiado", MessageBoxButton.OK, MessageBoxImage.Error)
                 End Try
            End Sub


    #End Region
    
    #Region "BOTONES"

        Private Sub btnRefrescar_Click(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs ) Handles btnRefrescar.Click  
    
        
            Dim idRegBit As Integer  
    

            Mouse.OverrideCursor = Cursors.Wait 
        
            Try
                 idRegBit =  CUtileria.GrabarBitacora ("Liquidación","Refresh","Actualiza información")
       
                    '1)Obtiene información de Fondos-Saldos de Decalog y se carga el Grid visual

                    lstFondosInter  = negocio.refrescar (negocio.obtenerFondos (CDefinicionesGrales.TiposFondo.FondoLiquidez))      
                    Me.grdFondoInter.ItemsSource = lstFondosInter 
                    Me.grdFondoInter.Items.Refresh ()

                    Me.btnBorrar.IsEnabled = True  
                    Me.btnFondeo.IsEnabled = True  
                    Me.btnExpExcel.IsEnabled = True  
            
            

                    CargarSaldosTotales ()


                     'Notificaciones para fondo-intermediario
                     For each fondo As  CFondoIntermediario In  lstFondosInter
                         AddHandler  fondo.PropertyChanged, AddressOf Fondoinver_PropertyChanged            
                     Next

                     Me.txtNumRow.Text = lstFondosInter.Count 


                     'Inicializar montos máximos


                     lstIntermediarios.Clear ()
                     

                     lstIntermediarios.Add (New CIntermediario (CIntermediario.enumConceptoInterLiq.Monto_maximo ))
                     lstIntermediarios.Add (New CIntermediario (CIntermediario.enumConceptoInterLiq.Monto_actual ))
                     lstIntermediarios.Add (New CIntermediario (CIntermediario.enumConceptoInterLiq.Monto_remanente))             


                     'Notificación para monto-intermediario
                     AddHandler  lstIntermediarios(CIntermediario.enumConceptoInterLiq.Monto_maximo).PropertyChanged, AddressOf Fondoinver_PropertyChanged            
             


                     grdMonMax.ItemsSource = lstIntermediarios  
                     grdMonMax.Items.Refresh ()
             


                CUtileria.CompletarRegBitacora (idRegBit )

            Catch ex As Exception         
                 Mouse.OverrideCursor = nothing
                    MessageBox.Show("Error TI500. " & ex.Message, "Proceso refrescar", MessageBoxButton.OK, MessageBoxImage.Error)
                 idRegBit =  CUtileria.GrabarBitacora ("Liquidación","Refresh","Error: " & ex.Message)
                 CUtileria.CompletarRegBitacora (idRegBit )
            End Try
    
            Mouse.OverrideCursor = Nothing 


        End Sub

        Private Sub btnBorrar_Click(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs ) Handles btnBorrar.Click  
        Dim numReg As Integer  
        Dim i As Integer 
        Dim j As Integer 


        Try
    

          Me.grdFondoInter.UnselectAllCells ()
           numReg = Me.grdFondoInter.Items.Count             
           For i = INICIOBLOQUEINTERMEDIARIOS  to FINCIOBLOQUEINTERMEDIARIOS 
             For j = 0 to numReg -1
                seleccionarcelda (Me.grdFondoInter,j,i) 
             Next
           Next     
            borraDatosSeleccionados(Me.grdFondoInter)  

            Me.grdFondoInter.UnselectAllCells  ()
          Catch ex As Exception
                    MessageBox.Show("Error TI500. No se permite la operación de borrado mientras se este editando alguna celda o " & ex.Message, "Borrado de celdas seleccionadas", MessageBoxButton.OK, MessageBoxImage.Exclamation)
          End Try
        End Sub

        Private Sub btnFondeo_Click(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs ) Handles btnFondeo.Click  

        Dim negocioLiq As New CLiquidezServicio ()

        Dim numIntermedActual As Integer = 0
        Dim auxRegBitFolDec   As CBitFolioDec 


        Dim i                 As Integer   
        Dim sumaTotal         As Double 
        Dim archivoSalida     As String = ""


        Dim sMsgError As String = ""
 

        Dim lstInterAux As List(Of CFondoIntermediario ) = Me.grdFondoInter.ItemsSource 

        Dim fechaHoy As String = lstInterAux(0).FechaLiq 
        Dim fechasig As String = lstInterAux(0).FechaVtoReporto  

        Dim idRegBit As Integer 
        Dim idRegBitAux As Integer 
 
        


        idRegBit =  CUtileria.GrabarBitacora ("Liquidación","Fondeo","Procesar...")

          Try
      
              For i = CFondoIntermediario.INDEXINICIOINTERMEDIARIO    to CFondoIntermediario.INDEXFININTERMEDIARIO  
                 numIntermedActual = ((i - CFondoIntermediario.INDEXINICIOINTERMEDIARIO)  + 1 )

                 sumaTotal =  negocioLiq.ObtenerImporteTotal (i,lstInterAux)   
                 if sumaTotal  <> 0 then 
                     If MessageBox.Show ("¿Desea procesar el intermediario " & numIntermedActual & " con un monto de " & String.Format("{0:C}",sumaTotal)     & "?","Procesar fondeo",MessageBoxButton.YesNo,MessageBoxImage.Question)  = MessageBoxResult.Yes then 
               

                        If negocioLiq.GenerarArchivoFondeo( i, lstInterAux ,NOMBREARCHIVO,RUTAARCHIVO, archivoSalida,fechaHoy,fechasig,CDefinicionesGrales.TiposFondo.FondoLiquidez )  = 0 then                    
                   
                           auxRegBitFolDec = New CBitFolioDec (CAreaFuncion.Funciones.Liquidez,numIntermedActual,archivoSalida,CBitFolioDec.estatusFolioDec.PENDIENTE)
                                      
                           if negocioLiq.GuardarFolioDecBit (auxRegBitFolDec,sMsgError) = False then 
                              idRegBitAux  =  CUtileria.GrabarBitacora ("Liquidación","Fondeo","No se pudo guardar el registro del archivo: " & archivoSalida & ". Error: " & sMsgError)
                               CUtileria.CompletarRegBitacora (idRegBitAux)  
                               sMsgError = ""
                           End If                                                                                                                                                                            
                                    negocioLiq.ejecutarProceso(RUTAARCHIVO  & TLOADERCOMMAND, PARAMTLOADER.Replace ("@archivosalida",RUTAARCHIVO & archivoSalida)) 
                                    archivoSalida = ""   
                                                                                                                                                                      
                        else
                            MessageBox.Show("El intermediario " & numIntermedActual & " no ha sido procesado: no hay importes para este intermediario u ocurrió algo inesperado en la generación del archivo.","Fondeo", MessageBoxButton.OK,MessageBoxImage.Exclamation )                    
                        End If
                                                               
                     End If

                 End If         
              Next 

      
              btnRefrescar_Click (Me.btnRefrescar, Nothing )
              CUtileria.CompletarRegBitacora (idRegBit)   


              MessageBox.Show("El proceso ha terminado " & vbCrLf & "Para visualizar los folios Decalog de respuesta correspondientes a las operaciones efectuadas, consulte la bitácora de folios." )
     

          Catch ex As Exception
             idRegBit =  CUtileria.GrabarBitacora ("Liquidación","Fondeo","Error: " & ex.Message)
             CUtileria.CompletarRegBitacora (idRegBit)
                    MessageBox.Show("Error TI500. Error fatal: " & ex.Message)
          End Try

        End Sub

        Private Sub btnExpExcel_Click(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs ) Handles btnExpExcel.Click 

            Dim xlsAplicacion As _Application
            Dim wbkLibro As Workbook
            Dim shtHoja As Worksheet


            Dim regInicial As Integer = 5 
    
            Dim colInicial As Integer = 0 
            Dim colInicialSTR As String  = "A"

            Dim rangoRegFinal As Integer 
            Dim rangoColFinalSTR As String = "R"


            xlsAplicacion  =CUtileria.ExportarAExcel (Me.grdFondoInter,regInicial,colInicial)
            wbkLibro = xlsAplicacion.ActiveWorkbook 
            shtHoja = wbkLibro.Sheets(1)

            'TITULO


            shtHoja.Range ("F3").Value = "Liquidación Decalog"
            shtHoja.Range ("F3").Font.Bold = True 
            shtHoja.Range ("F3").Font.Size = 15


            'FORMATO

            rangoRegFinal = Me.grdFondoInter.Items.Count  + regInicial 

    


            shtHoja.Cells(rangoRegFinal + 2, 1).value = "TOTAL"
            shtHoja.Cells(rangoRegFinal + 2, 2).value = Me.txtSaldoDisp.Text 
            shtHoja.Cells(rangoRegFinal + 2, 3).value = Me.txtOrdenPend.Text  
            shtHoja.Cells(rangoRegFinal + 2, 4).value =  Me.txtPendingCash.Text  
            shtHoja.Cells(rangoRegFinal + 2, 5).value =  Me.txtPendindAdj.Text 
            shtHoja.Cells(rangoRegFinal + 2, 6).value =  Me.txtSalDecalog.Text 
            shtHoja.Cells(rangoRegFinal + 2, 7).value =  negocio.ObtenerImporteTotal (CFondoIntermediario.ObtenerPosiciones("SaldoDecalogCalculado"),Me.grdFondoInter.ItemsSource).ToString ("$ ##,##0.00")  

            shtHoja.Cells(rangoRegFinal + 2, 8).value =  Me.txtInter1.Text  
            shtHoja.Cells(rangoRegFinal + 2, 9).value =  Me.txtInter2.Text
            shtHoja.Cells(rangoRegFinal + 2, 10).value =  Me.txtInter3.Text
            shtHoja.Cells(rangoRegFinal + 2, 11).value =  Me.txtInter4.Text 
            shtHoja.Cells(rangoRegFinal + 2, 12).value =  Me.txtInter5.Text 
            shtHoja.Cells(rangoRegFinal + 2, 13).value =  Me.txtInter6.Text 
            shtHoja.Cells(rangoRegFinal + 2, 14).value =  Me.txtInter7.Text 
            shtHoja.Cells(rangoRegFinal + 2, 15).value =  Me.txtInter8.Text 
            shtHoja.Cells(rangoRegFinal + 2, 16).value =  Me.txtInter9.Text 
    


            shtHoja.Range (colInicialSTR & regInicial.ToString & ":" &  rangoColFinalSTR & (regInicial).ToString   ).Font.Bold =True 
            shtHoja.Cells.EntireColumn.AutoFit   
            shtHoja.Cells.EntireRow.AutoFit   
    
            shtHoja.Range (colInicialSTR & (rangoRegFinal + 2).ToString & ":" &  rangoColFinalSTR & ((rangoRegFinal + 2).ToString).ToString).Font.Bold =True 

            shtHoja.Range("B" & (regInicial + 1).ToString & ":" & "P" & (rangoRegFinal + 2).ToString ).NumberFormat = "#,##0.00####"
            shtHoja.Range("Q" & (regInicial + 1).ToString & ":" & "R" & (rangoRegFinal).ToString ).NumberFormat = "dd/mm/yyyy"
    

        End Sub

    #End Region

    #Region "NOTIFICACION DE CAMBIO DE VALOR DE UNA PROPIEDAD"

            Private Sub Fondoinver_PropertyChanged(sender As Object, e As PropertyChangedEventArgs)
              
                      Dim interMontoMax       As CIntermediario  =  grdMonMax.Items(CIntermediario.enumConceptoInterLiq.Monto_maximo)
                      Dim interMontoActual    As CIntermediario  =  grdMonMax.Items(CIntermediario.enumConceptoInterLiq.Monto_actual )
                      Dim interMontoRemanente As CIntermediario  =  grdMonMax.Items(CIntermediario.enumConceptoInterLiq.Monto_remanente)
               
              
                    Try
                        Select Case e.PropertyName      

                          Case "SalDisponible"
                               txtSaldoDisp.Text = negocio.ObtenerImporteTotal (CFondoIntermediario.ObtenerPosiciones("SalDisponible"),lstFondosInter).ToString ("$ ##,##0.00")                       
                          Case "OrdenPend"
                               txtOrdenPend.Text  = negocio.ObtenerImporteTotal (CFondoIntermediario.ObtenerPosiciones("OrdenPend"),lstFondosInter).ToString ("$ ##,##0.00")  
                          Case "PendingCash"
                               txtPendingCash.Text  = negocio.ObtenerImporteTotal (CFondoIntermediario.ObtenerPosiciones("PendingCash"),lstFondosInter).ToString ("$ ##,##0.00")  
                          Case "PendingCashAjust"
                               txtPendindAdj.Text  =  negocio.ObtenerImporteTotal (CFondoIntermediario.ObtenerPosiciones("PendingCashAjust"),lstFondosInter).ToString ("$ ##,##0.00")  
                          Case "SaldoDecalogT"
                               txtSalDecalog.Text  =  negocio.ObtenerImporteTotal (CFondoIntermediario.ObtenerPosiciones("SaldoDecalogT"),lstFondosInter).ToString ("$ ##,##0.00")  
                          Case "Intermediario1"
                               txtInter1.Text  = negocio.ObtenerImporteTotal (CFondoIntermediario.ObtenerPosiciones("Intermediario1"),lstFondosInter).ToString ("$ ##,##0.00")  
                               interMontoActual.Intermediario1 = txtInter1.Text
                               interMontoRemanente.Intermediario1 = interMontoMax.Intermediario1 - interMontoActual.Intermediario1                    
                          Case "Intermediario2"
                               txtInter2.Text = negocio.ObtenerImporteTotal (CFondoIntermediario.ObtenerPosiciones("Intermediario2"),lstFondosInter).ToString ("$ ##,##0.00")  
                               interMontoActual.Intermediario2 = txtInter2.Text
                               interMontoRemanente.Intermediario2 = interMontoMax.Intermediario2 - interMontoActual.Intermediario2
                          Case "Intermediario3"
                               txtInter3.Text = negocio.ObtenerImporteTotal (CFondoIntermediario.ObtenerPosiciones("Intermediario3"),lstFondosInter).ToString ("$ ##,##0.00")  
                               interMontoActual.Intermediario3 = txtInter3.Text
                               interMontoRemanente.Intermediario3 = interMontoMax.Intermediario3 - interMontoActual.Intermediario3
                          Case "Intermediario4"
                               txtInter4.Text = negocio.ObtenerImporteTotal (CFondoIntermediario.ObtenerPosiciones("Intermediario4"),lstFondosInter).ToString ("$ ##,##0.00")  
                               interMontoActual.Intermediario4 = txtInter4.Text
                               interMontoRemanente.Intermediario4 = interMontoMax.Intermediario4 - interMontoActual.Intermediario4
                          Case "Intermediario5"
                               txtInter5.Text = negocio.ObtenerImporteTotal (CFondoIntermediario.ObtenerPosiciones("Intermediario5"),lstFondosInter).ToString ("$ ##,##0.00")  
                               interMontoActual.Intermediario5 = txtInter5.Text
                               interMontoRemanente.Intermediario5 = interMontoMax.Intermediario5 - interMontoActual.Intermediario5
                          Case "Intermediario6"
                               txtInter6.Text = negocio.ObtenerImporteTotal (CFondoIntermediario.ObtenerPosiciones("Intermediario6"),lstFondosInter).ToString ("$ ##,##0.00")  
                               interMontoActual.Intermediario6 = txtInter6.Text
                               interMontoRemanente.Intermediario6 = interMontoMax.Intermediario6 - interMontoActual.Intermediario6
                          Case "Intermediario7"
                               txtInter7.Text = negocio.ObtenerImporteTotal (CFondoIntermediario.ObtenerPosiciones("Intermediario7"),lstFondosInter).ToString ("$ ##,##0.00")  
                               interMontoActual.Intermediario7 = txtInter7.Text
                               interMontoRemanente.Intermediario7 = interMontoMax.Intermediario7 - interMontoActual.Intermediario7
                          Case "Intermediario8"
                               txtInter8.Text = negocio.ObtenerImporteTotal (CFondoIntermediario.ObtenerPosiciones("Intermediario8"),lstFondosInter).ToString ("$ ##,##0.00")  
                               interMontoActual.Intermediario8 = txtInter8.Text
                               interMontoRemanente.Intermediario8 = interMontoMax.Intermediario8 - interMontoActual.Intermediario8
                          Case "Intermediario9"
                               txtInter9.Text = negocio.ObtenerImporteTotal (CFondoIntermediario.ObtenerPosiciones("Intermediario9"),lstFondosInter).ToString ("$ ##,##0.00")  
                               interMontoActual.Intermediario9 = txtInter9.Text
                               interMontoRemanente.Intermediario9 = interMontoMax.Intermediario9 - interMontoActual.Intermediario9
                                                                                                                                                                                              
                        End Select 
                             

                    


                    Catch ex As Exception
                                MessageBox.Show("Error TI500. Error al intentar calcular los importes totales: " & ex.Message, "Obtener totales", MessageBoxButton.OK, MessageBoxImage.Exclamation)
                    End Try
        

        End Sub


    #End Region


#End Region

  #Region "FUNCIONES DE APOYO A EVENTOS"


   #Region "Funciones por grid"

            Private Sub borraDatosSeleccionados(ByRef gridDeDatos As DataGrid) 

                Dim lstInterAux As List(Of CFondoIntermediario)
        
                lstInterAux = gridDeDatos.ItemsSource 
        
                Try
                      For each celda As DataGridCellInfo in gridDeDatos.SelectedCells            
                          Dim col As Integer = celda.Column.DisplayIndex   
                          Dim row As Integer = gridDeDatos.Items.IndexOf  (CType(celda.Item,CFondoIntermediario ))            
                  
                          If col > LIMITECOLUMNASOLOCOPIADO AND  (col > LIMITECOLUMNASOLOCOPIADO and col <= FINCIOBLOQUEINTERMEDIARIOS) then 
                          
                              Dim rowData as DataGridRow  = gridDeDatos.ItemContainerGenerator.ContainerFromIndex(row)
                              Dim cellContent As object = gridDeDatos.Columns(col).GetCellContent(rowData)                              
                              
                             cellContent.Text = String.Format ("{0:N}", CFondoIntermediario.ValorInicalColumna (col) )         
                             lstInterAux (row)(col) =  CFondoIntermediario.ValorInicalColumna (col)
                                  

                          End If 

                       Next
                             
                Catch ex As Exception
                    Throw ex    
                End Try


            End Sub
        
            Private Sub borraDatosSeleccionadosMontoMax(ByRef gridDeDatos As DataGrid) 

                Dim lstInterAux As List(Of CIntermediario)
        
                lstInterAux = gridDeDatos.ItemsSource 
        
                Try
                      For each celda As DataGridCellInfo in gridDeDatos.SelectedCells            
                          Dim col As Integer = celda.Column.DisplayIndex   
                          Dim row As Integer = gridDeDatos.Items.IndexOf  (CType(celda.Item,CIntermediario ))            

                          If (col > LIMITECOLUMNASOLOCOPIADO_MON) and (row < LIMITERENGLONSOLOCOPIADO_MON ) then

                              Dim rowData as DataGridRow  = gridDeDatos.ItemContainerGenerator.ContainerFromIndex(row)
                              Dim cellContent As object = gridDeDatos.Columns(col).GetCellContent(rowData)
                              cellContent.Text = String.Format("{0:N2}", CIntermediario.ValorInicalColumna (col))                                
                              lstInterAux (row)(col) =  CIntermediario.ValorInicalColumna (col)

                          End If 

                       Next
                             
                Catch ex As Exception
                    Throw ex    
                End Try


              End Sub

    
            Private Function  AgregarMenuContextual(ByVal opcion As ConfigMenuContextual) As ContextMenu 
                Dim miMenuContextual     As New ContextMenu
                Dim mnuCopia             As new System.Windows.Controls.MenuItem 
                Dim mnuPegar             As new System.Windows.Controls.MenuItem


 
               mnuCopia.Header = "Copiar"
               miMenuContextual.Items.Add(mnuCopia)
               AddHandler mnuCopia.Click,AddressOf  mnuCopiar_click


               'Este case esta preparado para extender la funcionalidad de las opciones del menú contextual
               Select Case opcion 
                  Case ConfigMenuContextual.COPIADO_Y_PEGADO 
                      mnuPegar.Header = "Pegar"  
                      miMenuContextual.Items.Add(mnuPegar)
                      AddHandler mnuPegar.Click,AddressOf  mnuPegar_click
               End Select

               Return miMenuContextual 

            End Function 
    
            Private Function  AgregarMenuContextualMontosMax(ByVal opcion As ConfigMenuContextual) As ContextMenu 
                Dim miMenuContextual     As New ContextMenu
                Dim mnuCopia             As new System.Windows.Controls.MenuItem 
                Dim mnuPegar             As new System.Windows.Controls.MenuItem
 
               mnuCopia.Header = "Copiar"
               miMenuContextual.Items.Add(mnuCopia)
               AddHandler mnuCopia.Click,AddressOf  mnuCopiarMontoMax_click


               'Este case esta preparado para extender la funcionalidad de las opciones del menú contextual
               Select Case opcion 
                  Case ConfigMenuContextual.COPIADO_Y_PEGADO 
                      mnuPegar.Header = "Pegar"  
                      miMenuContextual.Items.Add(mnuPegar)
                      AddHandler mnuPegar.Click,AddressOf  mnuPegarMontoMax_click 
               End Select

               Return miMenuContextual 

            End Function 

    #End Region 

   #Region  "Funciones comunes"
    
    Private Sub pegarDatos(ByRef gridDeDatos As DataGrid, ByVal sTipo As String, ByVal condicion As CUtileria.Condiciones)

        Dim lstInterAux As object = gridDeDatos.ItemsSource  
        Dim datos As CDatosEnFormatoX 
        dim ttipo As System.type  = Type.GetType(sTipo)



        Dim bCONDICIONNONEGATIVOS = False 
        Dim bCONDICIONMAYOTMONTOMAX = False 

        
        datos = CUtileria.ObtenerDatosClipboard (vblf,vbTab)
        
        '1) Validaciones: obtener información del portapapeles
        
           If datos.Datos.length = 0 then 
              Exit sub
           End If
        
        
          If datos is Nothing then 
             Throw New Exception ("No se pudo copiar los datos")                              
          End If
        
        '2) Validaciones: compatibilidad  
        
           Dim colTot As Integer = gridDeDatos.Columns.Count    
           Dim rowTot As Integer = gridDeDatos.Items.Count   
          
           Dim colActual As Integer =  gridDeDatos.CurrentCell.Column.DisplayIndex         
           Dim rowActual As Integer = gridDeDatos.Items.IndexOf  (CTypeDynamic(gridDeDatos.CurrentCell.Item ,ttipo)) 
        
        
            'Validar renglones
              
             If datos.NumeroRenglones  > ((rowTot - (rowActual + 1)) + 1)  then 
                Throw New Exception ("No coinciden las dimensiones de datos a pegar (R)")                                              
             End If
        
             If datos.NumeroColumnas.Max   > ((colTot - (colActual + 1)) + 1 )  then 
                Throw New Exception ("No coinciden las dimensiones de datos a pegar (C)")                                                                                              
             End If
        
          '2) Realizar copiado  
        
             Dim i As Integer = 0
             Dim j As Integer = 0
        
             Dim coontador As Integer = 0
             Dim limRow As Integer = (rowActual +  (datos.NumeroRenglones - 1))
             
             gridDeDatos.UnselectAllCells()
        
        
             Try
               
               For i = rowActual to limRow
                    Dim limCol As Integer = (colActual + (datos.NumeroColumnas(coontador) - 1))
                    
                    For j= colActual to limCol

                         

                         If j > FINCIOBLOQUEINTERMEDIARIOS THEN 
                             Continue For   
                         End If

                         If datos.Datos(i-rowActual)(j-colActual) <> vbLf and  (Not CType(datos.Datos(i-rowActual)(j-colActual),String).Trim ().Equals ("") ) then
                             Dim row as DataGridRow  = gridDeDatos.ItemContainerGenerator.ContainerFromIndex(i)
                             Dim cellContent As Object  = gridDeDatos.Columns(j).GetCellContent(row)                      
                             Dim auxImp As Double 
                             auxImp = CType (datos.Datos(i-rowActual)(j-colActual),Double)                                                          
                         
                             Select Case condicion

                                  Case CUtileria.Condiciones.pegarMonMaxLiq 
                                       
                                      if  j > LIMITECOLUMNASOLOCOPIADO_MON  and i < LIMITERENGLONSOLOCOPIADO_MON then 
                                          lstInterAux (i)(j) = auxImp
                                          cellContent.Text = String.Format ("{0:N}",lstInterAux (i)(j))
                                          seleccionarcelda( gridDeDatos, i,j)
                                      End If
                                
                                                    
                                  Case Else 
                                      'Condición para no pegar importes que sobrepasen el monto máximo
                                      If  lstIntermediarios(CIntermediario.enumConceptoInterLiq.Monto_maximo).Columna((j  -   INICIOBLOQUEINTERMEDIARIOS + 1))  >=  lstIntermediarios(CIntermediario.enumConceptoInterLiq.Monto_actual).Columna ((j  -   INICIOBLOQUEINTERMEDIARIOS + 1)) + auxImp  then 

                                          lstInterAux (i)(j) = auxImp
                                          cellContent.Text = String.Format ("{0:N}",lstInterAux (i)(j))
                                          seleccionarcelda( gridDeDatos, i,j)
                                      Else 
                                          bCONDICIONMAYOTMONTOMAX = True 

                                      end If 
                             End Select

                                                                                                                   
                             If auxImp < 0 then
                                bCONDICIONNONEGATIVOS = True  
                             End If 
                                                     

                         End If                 
                    Next
                    coontador+=1
                Next
                                      
                   

             If bCONDICIONMAYOTMONTOMAX = True then
                 Throw New Exception ("No se pudieron pegar todos los datos, ya que algunos de ellos sobrepasaban el importe máximo asignado")                 
             End If
           

             If bCONDICIONNONEGATIVOS = True then               
                  Throw New Exception ("Los valores negativos no pudieron ser pegados: no están permitidos")                 
             End If
                                 
        
             Catch ex As Exception                          
                     
                   
                 If bCONDICIONMAYOTMONTOMAX = True or bCONDICIONNONEGATIVOS = True  then 
                     Throw ex                                           
                 else
                     Throw New Exception ("No se pudo terminar de copiar los datos debido a que no coinciden con el formato especificado para cada celda",ex)                               
                 End If

                 
             End Try


End Sub
    
    Private function copiarCeldas(ByRef gridDeDatos As DataGrid, ByVal sTipo As String) As Boolean 

    dim ttipo As System.type  = Type.GetType(sTipo)
    
    Try
    
         Dim lstInterAux As Object  = gridDeDatos.ItemsSource
          

         Dim datos As new system.Text.StringBuilder 
         Dim copiadoCorrecto As Boolean  = True 


         Dim colIni As Integer = Integer.MaxValue   
         Dim rowIni As Integer = Integer.MaxValue  

         Dim colFin As Integer = Integer.MinValue 
         Dim rowFin As Integer = Integer.MinValue       


         Dim i As Integer = 0
         Dim j As Integer = 0


         Dim columnasIndex(gridDeDatos.SelectedCells.Count - 1) As Integer
         Dim renglonesIndex(gridDeDatos.SelectedCells.Count - 1) As Integer

        For Each celda As DataGridCellInfo In gridDeDatos.SelectedCells 

            renglonesIndex(i) = gridDeDatos.Items.IndexOf (CTypeDynamic(celda.Item, ttipo))
            columnasIndex(j) = celda.Column.DisplayIndex           
            i+=1
            j+=1
        Next


           rowIni = renglonesIndex.Min () 
           rowFin = renglonesIndex.Max () 

           colIni = columnasIndex.Min ()
           colFin = columnasIndex.Max ()


         For i = rowIni to rowFin 
            For j = colIni  to colFin 
                If EsSeleccionadaLaCelda(gridDeDatos, i,j) then 
                     datos.Append ( lstInterAux(i)(j).ToString() & vbTab )
                else          
                    copiadoCorrecto = False 
                    GoTo fuera
                End If        
            Next
    
            datos.Remove (datos.Length -1,1)
            datos.Append (vblf)
         Next
 

         datos.Remove (datos.Length -1,1)

 

         fuera:
         If copiadoCorrecto = True then 
            Clipboard.Clear ()
            Clipboard.SetText (datos.ToString () )
            Return true
         else
           Return False  
         End If


 Catch ex As Exception

     Throw ex
     
 End Try




End function
    
    Private function EsSeleccionadaLaCelda(ByRef gridDeDatos As DataGrid,  ByVal indexRow As Integer, ByVal indexCol As Integer ) As Boolean 

        Dim row as DataGridRow  = gridDeDatos.ItemContainerGenerator.ContainerFromIndex(indexRow)
        Dim cellContent As Object  = gridDeDatos.Columns(indexCol).GetCellContent(row)     
 

          Dim objDepend As DependencyObject = cellContent
          Dim celda As DataGridCell = Nothing 

           While not objDepend is Nothing 

                If objDepend.GetType().Name = "DataGridCell" then 
                   celda = objDepend           
           
                   If celda.IsSelected = True   then                                       
                       Return true
                    else
                       Return False 
                   End If
                                           
                End If

               objDepend = VisualTreeHelper.GetParent (objDepend)   
          End While

          Return False

    End Function 
    
    Private Sub seleccionarcelda(ByRef gridDeDatos As DataGrid, ByVal indexRow As Integer, ByVal indexCol As Integer)
  
        Dim row as DataGridRow  = gridDeDatos.ItemContainerGenerator.ContainerFromIndex(indexRow)
        Dim cellContent As TextBlock = gridDeDatos.Columns(indexCol).GetCellContent(row)     


          Dim objDepend As DependencyObject = cellContent
          Dim celda As DataGridCell = Nothing 


           While not objDepend is Nothing 

                If objDepend.GetType().Name = "DataGridCell" then 
                   celda = objDepend           
           
                   If celda.IsSelected = false  then                                        
                       celda.IsSelected = True                  
                       celda.Focus ()
                       Exit While                
                   End If
                                           
                End If

               objDepend = VisualTreeHelper.GetParent (objDepend)   
          End While

    End Sub
    
    Private Sub CargarSaldosTotales()
     

        Try


 

        txtSaldoDisp.Text = negocio.ObtenerImporteTotal (CFondoIntermediario.ObtenerPosiciones("SalDisponible"),lstFondosInter).ToString ("$ ##,##0.00")  
        txtOrdenPend.Text  = negocio.ObtenerImporteTotal (CFondoIntermediario.ObtenerPosiciones("OrdenPend"),lstFondosInter).ToString ("$ ##,##0.00")  
        txtPendingCash.Text  = negocio.ObtenerImporteTotal (CFondoIntermediario.ObtenerPosiciones("PendingCash"),lstFondosInter).ToString ("$ ##,##0.00")  
        txtPendindAdj.Text  =  negocio.ObtenerImporteTotal (CFondoIntermediario.ObtenerPosiciones("PendingCashAjust"),lstFondosInter).ToString ("$ ##,##0.00")  
        txtSalDecalog.Text  =  negocio.ObtenerImporteTotal (CFondoIntermediario.ObtenerPosiciones("SaldoDecalogT"),lstFondosInter).ToString ("$ ##,##0.00")  



        txtInter1.Text  = negocio.ObtenerImporteTotal(CFondoIntermediario.ObtenerPosiciones("Intermediario1"),lstFondosInter).ToString ("$ ##,##0.00")  
        txtInter2.Text = negocio.ObtenerImporteTotal (CFondoIntermediario.ObtenerPosiciones("Intermediario2"),lstFondosInter).ToString ("$ ##,##0.00")  
        txtInter3.Text = negocio.ObtenerImporteTotal (CFondoIntermediario.ObtenerPosiciones("Intermediario3"),lstFondosInter).ToString ("$ ##,##0.00")  
        txtInter4.Text = negocio.ObtenerImporteTotal (CFondoIntermediario.ObtenerPosiciones("Intermediario4"),lstFondosInter).ToString ("$ ##,##0.00")  
        txtInter5.Text = negocio.ObtenerImporteTotal (CFondoIntermediario.ObtenerPosiciones("Intermediario5"),lstFondosInter).ToString ("$ ##,##0.00")  
        txtInter6.Text = negocio.ObtenerImporteTotal (CFondoIntermediario.ObtenerPosiciones("Intermediario6"),lstFondosInter).ToString ("$ ##,##0.00")  
        txtInter7.Text = negocio.ObtenerImporteTotal (CFondoIntermediario.ObtenerPosiciones("Intermediario7"),lstFondosInter).ToString ("$ ##,##0.00")  
        txtInter8.Text = negocio.ObtenerImporteTotal (CFondoIntermediario.ObtenerPosiciones("Intermediario8"),lstFondosInter).ToString ("$ ##,##0.00")  
        txtInter9.Text = negocio.ObtenerImporteTotal (CFondoIntermediario.ObtenerPosiciones("Intermediario9"),lstFondosInter).ToString ("$ ##,##0.00")  

        Catch ex As Exception
                    MessageBox.Show("Error TI500. Error al intentar calcular los importes totales: " & ex.Message, "Obtener totales", MessageBoxButton.OK, MessageBoxImage.Exclamation)
        End Try



End Sub

    Private Function  ObtenerCelda(ByRef miDataGrid As DataGrid, ByVal indexRow As Integer, ByVal indexCol As Integer  ) As DataGridCell 

        Try
              Dim row as DataGridRow  = miDataGrid.ItemContainerGenerator.ContainerFromIndex(indexRow)            
              Dim cellContent As Object  = miDataGrid.Columns(indexCol).GetCellContent(row)     
 
              Dim objDepend As DependencyObject = cellContent
              Dim celda As DataGridCell = Nothing       

               While not objDepend is Nothing 

                    If objDepend.GetType().Name = "DataGridCell" then 
                       celda = objDepend           
                       Return celda                                                      
                    End If
                   objDepend = VisualTreeHelper.GetParent (objDepend)   
              End While
        Catch ex As Exception
            Throw ex
        End Try

        Return Nothing 
    End Function

    #End Region 


  #End Region

  Public Sub New()     
           
      InitializeComponent()  
      negocio = New CLiquidezServicio() 
      negocio.CargarParametrosLiquidez(RUTAARCHIVO,NOMBREARCHIVO,TLOADERCOMMAND,PARAMTLOADER)     
      Mouse.OverrideCursor = Nothing  
                                       
   End Sub



End Class



#Region "Clases de apoyo para validación y formatos de entrada"

public Class CCondicionNumNegativo
    Implements IValueConverter


    Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
        If IsNumeric(value)  then 
            Dim valor As Double  =  CType (value,DOUBLE)  

            If valor < 0  then 
                Return Brushes.Red 
            Else                 
                Return Brushes.Black                  
            End If
         else
             Return Brushes.Black 
        End If 


    End Function

    Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
        Throw New Exception 
    End Function

End Class


public Class CFormatoCerosInter
    Implements IValueConverter


    Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
        If IsNumeric(value) then 
            Dim valor As Double  =  CType (value,DOUBLE)  

            If valor = 0 then
               Return Brushes.Transparent 
            else
               Return Brushes.Black                            
            End If 

        Else 
            Return Brushes.Black                            
        End If 

    End Function

    Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
        Throw New Exception 
    End Function

End Class



#End Region


